package com.example.management.controller;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.management.utils.CommonUtil;
import com.example.management.utils.JsonData;
import com.google.code.kaptcha.Producer;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    @Autowired
    private Producer captchaProducer;
    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("/get")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {
        String text = captchaProducer.createText();
        redisTemplate.opsForValue().set(getCaptchaKey(request), text, 30, TimeUnit.SECONDS);
        BufferedImage image = captchaProducer.createImage(text);
        try {
            ServletOutputStream servletOutputStream = response.getOutputStream();
            ImageIO.write(image, "png", servletOutputStream);
            servletOutputStream.flush(); servletOutputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    private String getCaptchaKey(HttpServletRequest request) {
        String ip = CommonUtil.getIpAddr(request);
        String userInfo = request.getHeader("User-Agent");
        String md5 = CommonUtil.MD5(ip + userInfo);
        return "captcha:" + md5;
    }
    @GetMapping("/check")
    public JsonData checkCaptcha(String captcha, HttpServletRequest request) {
        Object value = redisTemplate.opsForValue().get(getCaptchaKey(request));
        if (value == null) {
            return JsonData.buildError("验证码已过期, 请刷新页面");
        }
        if (captcha.equals(value)) {
            return JsonData.buildSuccess(null,"验证成功");
        }
        return JsonData.buildError("验证失败");
    }
}

